/* eslint-disable radix, no-shadow */
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Button, Icon, Modal, Row, Col, Input, message, Divider, Table, Upload, Progress } from 'antd';
import * as qiniu from 'qiniu-js';
import {API_DOMAIN, QINIU_DOMAIN} from '../../../utils/constants';

import changeMenu from '../../../actions/menu';
import FileAction from '../../../actions/file';
import API from '../../../api/files/index';
import TokenAPI from '../../../api/auth/index';
const { Search } = Input;
import TMTable from '../TMTable/Table';
import './FileList.scss';

const EditableCell = ({ editable, value, onChange }) => (
    <div>
        {editable
            ? <Input style={{ margin: '-5px 0' }} value={value} onChange={e => onChange(e.target.value)} />
            : value
        }
    </div>
);

class FileList extends Component {
    constructor (props) {
        super(props);
        const columns = [{
            title: '名称',
            key: 'nickname',
            dataIndex: 'nickname',
            width: '30%',
            render: (text, record) => {
                const { format } = record;
                let children = '';
                if (format === 'folder') {
                    children = ( <Icon type="file-pdf" />);
                } else if (format === 'pdf') {
                    children = ( <Icon type="folder" />);
                }
                if(record.status == "complete" || record.status == ""){
                    return (
                        <span onClick={() => this.clickCol(record)} style={{ cursor: 'pointer' }}>
                {children}
                            <span style={{ marginLeft: 10 }}>
                  {record.nickname}
                                {
                                    record.format !== 'folder' ?
                                        (<span>.{record.format}</span>) : ''
                                }
                </span>
              </span>
                    );
                }else{
                    return (
                        <span style={{ cursor: 'pointer' }}>
                {children}
                            <span style={{ marginLeft: 10,color:'#bababa' }}>
                  {record.nickname}
                                {
                                    record.format !== 'folder' ?
                                        (<span>.{record.format}</span>) : ''
                                }
                </span>
              </span>
                    );
                }
            },
        }, {
            title: '',
            key: '',
            dataIndex: '',
            width: '5%',
            render: (text, record) => {
                if(record.status == "running"){
                    return (
                        <span><img style={{ width: 24}} src="https://files.pansheng.com/img_loading_documents.gif" alt=""/></span>
                    );
                }else if(record.status == "complete" || record.status == "" ){
                    return (
                    <span onClick={() => this.clickCol(record)}></span>
                );
                }else if(record.status == "fail"){
                    return(
                        <span style={{color:'red'}}>文件错误，请联系管理员</span>
                    );
                }
            },
        },
        {
            title: '上传时间',
            key: 'createdAt',
            dataIndex: 'createdAt',
            width: '30%',
            render: (text, record) => {
                Date.prototype.Format = function (fmt) { //author: meizz 
                    var o = {
                        "M+": this.getMonth() + 1, //月份 
                        "d+": this.getDate(), //日 
                        "h+": this.getHours(), //小时 
                        "m+": this.getMinutes(), //分 
                        "s+": this.getSeconds(), //秒 
                        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
                        "S": this.getMilliseconds() //毫秒 
                    };
                    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
                    for (var k in o)
                    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                    return fmt;
                }
                var unixTimestamp = new Date(record.createdMillis);
                var commonTime = unixTimestamp.Format("yyyy-MM-dd hh:mm:ss");  
                if(record.status == "complete" || record.status == "" ){
                    return (
                        <span onClick={() => this.clickCol(record)}  style={{ cursor: 'pointer' }}>
                {commonTime}</span>
                    );
                }else{
                    return (
                        <span  style={{ cursor: 'pointer' }}>
                {commonTime}</span>
                    );
                }
            },
        }, {
            title: '文件大小',
            key: 'size',
            dataIndex: 'size',
            width: '20%',
            render: (text, record) => {
                const { size } = record;
                const ONE_KB = 1024;
                let val = '';
                if (size && size < ONE_KB) {
                    val = `${size}k`;
                } else if (size >= ONE_KB && size < ONE_KB * ONE_KB) {
                    val = `${parseInt(size / ONE_KB)}KB`;
                } else if (size >= ONE_KB * ONE_KB) {
                    val = `${parseInt(size / ONE_KB / ONE_KB)}MB`;
                }
                return (
                    <span>{val}</span>
                );
            },
        },{
            title: '操作',
            key: 'operate',
            dataIndex: 'operate',
            width: '20%',
            render: (text, record) => {
                if(this.props.tabIndex == "1"){
                    return (<span><a role="button" tabIndex="0" onClick={() => this.deleteFile(record.id)}>删除</a></span>
                );
                }else if(this.props.tabIndex == "2"){
                    return (<span><a role="button" tabIndex="0" style={{color:'grey'}} onClick={() => this.deleteFileUnable(record.id)}>删除</a></span>
                    );
                }
                    
            },
        }
        ];
        let currentId = '';
        switch (this.props.tabIndex) {
            case 1:
                currentId = JSON.parse(window.sessionStorage.getItem('account')).id;
                break;
            case 2:
                currentId = 'teams';
                break;
            default:
                break;
        }
        console.log(currentId);
        this.state = {
            columns,
            currentId,
            dirCount: 0,
            fileCount: 0,
            dataSource: [],
            visibleOfDir: false,
            visibleOfFile: false,
            dirName: '',
            uploadedFiles: [],
            name:"",
            nameList:[],
        };
    }
    seperateFiles = (files, type) => files.filter(item => item.format === type);
    orderFiles = (files, orderType) => files.sort((a, b) => (orderType === 'desc' ? a.createdAt < b.createdAt : a.createdAt > b.createdAt));
    getFileList = async (id) => {
        const response = await API.getFileList(id);
        const { code, data } = response;
        const childrenData = data.children;
        // var childrenData =[];
        // const originSearchData = this.props.searchData;
        // if(originSearchData == undefined){
        //     childrenData = data.children;
        // }else{
        //     childrenData = originSearchData;
        // }
            const folders = this.orderFiles(this.seperateFiles(childrenData, 'folder'), 'desc');
            const files = this.orderFiles(this.seperateFiles(childrenData, 'pdf'), 'desc');
            const dataSource = [...folders, ...files];
            this.setState({
                dataSource,
                dirCount: folders.length,
                fileCount: files.length,
            });
            return dataSource;
    }

    deleteFileUnable(){
        message.warning('没有权限删除');
    }

     clickCol(record){
        const { id, format } = record;
        if (format === 'folder') {
            this.getFileList(id);
            this.setState({
                currentId: id,
            })
            this.closeCall(id);
        } else {
            this.props.changeMenu('fileDetail');
            this.props.changeCurrentID(id);
        }
   }

    deleteFile(fireId){
        var parentId=null;
        this.getList(fireId).then((res)=>{
            parentId = res;
            if(parentId==null){
                return;
            }
            this.setState({
                currentId: parentId,
                nameList: null,
            })
        });
        const { confirm } = Modal;
        const self = this;
        confirm({
            title: '确认删除该文件？',
            content: '',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk () {
                self.handleDeleteFile(fireId);
            },
            onCancel () {
            },
        });
    }

    handleDeleteFile = async (fireId) => {
        const response = await API.deleteFlie(fireId);
        const { code } = response;
        this.setState({
            nameList: null,
        })
        if (code === 1) {
            message.success('删除成功');
            this.getFileList(this.state.currentId);
        }else{
            message.warning('有子文件夹，不允许直接删除');
        }
    }

    componentDidMount () {
            this.props.onRef(this);
            const id = this.state.currentId;
            this.getFileList(id);
    }

    componentWillReceiveProps (nextProps) {
        console.log(this.props);
        console.log(nextProps);
        // const originSearchData =nextProps.searchData;
        var currentFiledId = nextProps.fileId;
        var tabFileId = nextProps.tabFileId;
        if(currentFiledId !== ""){
            this.getList(currentFiledId).then((res)=>{
                parentId = res;
                if(parentId==null){
                    return;
                }else{
                    this.getName(parentId).then((res)=>{
                        var list = res;
                        if(list !== undefined){
                            if(list.length>0){
                                list = list.splice(0,1);
                            }
                            this.setState({
                                nameList: list
                            });
                        }else{
                            this.setState({
                                nameList: []
                            });
                        }
                        var callback =  this.props.returnName;
                        if(callback!=null&&_.isFunction(callback)){
                            callback(this.state.nameList);
                        }
                    });
                    this.setState({
                        currentId: parentId,
                        nameList: null,
                    })
                    this.getFileList(parentId);
                }
            });
        }else{
            this.setState({
                currentId: tabFileId,
            })
            this.getFileList(tabFileId);
        }
        //   var fileId = nextProps.tabFileId;
        //     if(fileId == "teams" || fileId == "5ac3661024aa9a000138c6a4"){
        //         this.getFileList(fileId);
        //     }else{
        //        const id =this.state.currentId;
        //        if(id == "teams" || id == "5ac3661024aa9a000138c6a4"){
        //         this.getFileList(id);
        //        }else{
        //         this.getFileList(currentFiledId);
        //         this.getName(currentFiledId).then((res)=>{
        //             var list = res;
        //             if(list !== undefined){
        //                 if(list.length>0){
        //                     list = list.splice(0,1);
        //                 }
        //                 this.setState({
        //                     nameList: list
        //                 });
        //             }else{
        //                 this.setState({
        //                     nameList: []
        //                 });
        //             }
        //             var callback =  this.props.returnName;
        //             if(callback!=null&&_.isFunction(callback)){
        //                 callback(this.state.nameList);
        //             }
        //         });
        //        }
        //     }
        // if(originSearchData.length>0){
        //     this.getFileList(originSearchData[0].id);
        // }else{
        //     this.getFileList(fileId);
        // }
    }

    handleAddDir = async () => {
        const accountId = JSON.parse(window.sessionStorage.getItem('account')).id;
        const { dirName } = this.state;
        if (!dirName.trim()) {
            message.warn('请输入文件夹名称');
        } else {
            const params = {
                nickname: dirName,
                fullname: dirName,
                format: 'folder',
                parent: this.state.currentId,
                tags: [],
            };
            // todo
            if(parent == undefined){
                params.parent = accountId;
            }
            const response = await API.addFileOrFolder(params);
            const { code } = response;
            if (code === 1) {
                message.success('添加成功');
                this.setState({
                    visibleOfDir: false,
                });
                this.getFileList(this.state.currentId);
            }
        }
    }

    handleHideModal = (key) => {
        this.setState({
            [key]: false,
        });
    }

    handleUploadFile = async () => {
        const accountId = JSON.parse(window.sessionStorage.getItem('account')).id;
        const uploadedFiles = this.state.uploadedFiles
        if (uploadedFiles.length === 0) {
            message.warn('请先上传文件');
        } else if (uploadedFiles.length === 1) {
            const params = {
                url: uploadedFiles[0].url,
                size: uploadedFiles[0].size,
                nickname: uploadedFiles[0].nickname,
                fullname: uploadedFiles[0].fullname,
                format: 'pdf',
                parent: this.state.currentId,
                tags: [],
                security: [
                    'agreement'
                ],
            }
            if(this.state.currentId == undefined){
                params.parent = accountId;
            }
            const response = await API.addFileOrFolder(params);
            const { code } = response;
            if (code === 1) {
                message.success('添加成功');
                this.setState({
                    visibleOfFile: false,
                }, () => {
                    this.getFileList(this.state.currentId);
                    this.timer = setInterval(
                        () => {
                            this.getFileList(this.state.currentId);
                        },
                        3000
                    );
                });
            }
        } else {
            const params = {
                parent: this.state.currentId,
                files: [...this.state.uploadedFiles]
            }
            const response = await API.batchUploadFile(params);
            const { code } = response;
            if (code === 1) {
                message.success('添加成功');
                this.setState({
                    visibleOfFile: false,
                }, () => {
                    this.getFileList(this.state.currentId);
                    this.timer = setInterval(
                        () => {
                            this.getFileList(this.state.currentId);
                        },
                        3000
                    );
                });
            }
        }
    }

    renderColumns (text, record, column) {
        return (
            <EditableCell
                editable={record.editable}
                value={text}
                onChange={value => this.handleChange(value, record.uid, column)}
            />
        );
    }
    handleChange (value, uid, column) {
        const newData = [...this.state.uploadedFiles];
        const target = newData.filter(item => uid === item.uid)[0];
        if (target) {
            target[column] = value;
            this.setState({ uploadedFiles: newData });
        }
    }
    remove (index) {
        const uploadedFiles = this.state.uploadedFiles
        uploadedFiles.splice(index, 1)
        this.setState({
            uploadedFiles
        })
    }
    edit (uid) {
        const newData = [...this.state.uploadedFiles];
        const target = newData.filter(item => uid === item.uid)[0];
        if (target) {
            target.editable = true;
            this.setState({ uploadedFiles: newData });
        }
    }
    save (uid) {
        const newData = [...this.state.uploadedFiles];
        const target = newData.filter(item => uid === item.uid)[0];
        if (target) {
            delete target.editable;
            this.setState({ uploadedFiles: newData });
            this.cacheData = newData.map(item => ({ ...item }));
        }
    }
    cancel (uid) {
        const newData = [...this.state.uploadedFiles];
        const target = newData.filter(item => uid === item.uid)[0];
        if (target) {
            Object.assign(target, this.cacheData.filter(item => uid === item.uid)[0]);
            delete target.editable;
            this.setState({ uploadedFiles: newData });
        }
    }
    finishUpload = ({ file }) => {
        const { status } = file.status;
        if (status === 'done') {
            this.state.uploadedFiles.filter((item, index) => {
                if (item.uid === file.uid) {
                    item.percent = 100;
                }
            });
        }
    }
    handleUpload = async ({ file }) => {
        const accountId = JSON.parse(window.sessionStorage.getItem('account')).id;
        const response = await TokenAPI.getUploadToken();
        const { code, data } = response;
        if (code === 1) {
            const fileName = file.name.substr(0, file.name.lastIndexOf('.'));
            const ext = file.name.substr(file.name.lastIndexOf('.') + 1);
            const fileObj = {
                uid: file.uid,
                size: file.size,
                nickname: fileName,
                fullname: file.name,
                url: '',
                parent: this.state.currentId,
                format: ext,
                percent: 0,
                tags: [],
                security: ['agreement'],
            };
            if(parent == undefined){
                param.parent = accountId;
            }
            this.setState({
                uploadedFiles: [...this.state.uploadedFiles, fileObj],
            });
            const token = data;
            const config = {
                useCdnDomain: true,
            };
            const putExtra = {
                fname: '',
                params: {},
                mimeType: null,
            };
            const next = async ({ total }) => {
                const { percent } = total;
                const { uploadedFiles } = this.state;
                uploadedFiles.filter((item, index) => {
                    if (item.uid === file.uid) {
                        const tempObj = Object.assign({}, item, { percent: parseInt(percent) });
                        uploadedFiles.splice(index, 1, tempObj);
                        this.setState({ uploadedFiles });
                    }
                });
            };
            const complete = async (res) => {
                const url = `${QINIU_DOMAIN}/${res.key}`;
                const response = await TokenAPI.getDownloadUrl(url);
                const { code, data } = response;
                if (code === 1) {
                    let uploadedFiles= this.state.uploadedFiles
                    const tempObj = uploadedFiles[uploadedFiles.length - 1]
                    tempObj.url = data
                    uploadedFiles.splice(uploadedFiles.length - 1, 1, tempObj)
                    this.setState({
                        uploadedFiles
                    })
                }
            };
            const observable = qiniu.upload(file, null, token, putExtra, config);
            observable.subscribe(next, undefined, complete);
        } else {
            // message.error('token获取失败');
        }
    }

    getList = async (id) => {
        const response = await API.getFileList(id);
        const { code, data } = response;
        if (code === 1) {
            var parentId = response.data.parent;
            return parentId;
        }
    }

    //获取点击的文件夹名称
    getName = async (id) => {
        const response = await API.getFileList(id);
        const { code, data } = response;
        if (code === 1) {
            var name = response.data.nickname;
            var path = response.data.path;
            var list =path;
            if(list[0].id == "teams"){
                list.splice(0,1);
            }else{
                list.splice(0,2);
            }
            return list;
        }
    }

    closeTitle = (id) => {
            this.getFileList(id);
            this.closeCall(id);
    }

    closeBackTitle = (id) => {
        var parentId=null;
        this.getList(id).then((res)=>{
            parentId = res;
            if(parentId==null){
                return;
            }
            this.setState({
                currentId: parentId,
                nameList: null,
            })
            this.closeCall(parentId);
            this.getFileList(parentId);
        });
    }

    //标题回调，传给父组件
    closeCall(id){
        var list = [];
        this.getName(id).then((res)=>{
            nameList = res;
           // if(nameList.length <0){
           //     return;
           // }
            this.setState({
                nameList: nameList,
            })
            var callback =  this.props.returnName;
            if(callback!=null&&_.isFunction(callback)){
                callback(this.state.nameList);
            }
        });
    }

   //返回按钮事件
    closeBack(){
        var id = this.state.currentId;
        var parentId=null;
        this.getList(id).then((res)=>{
            parentId = res;
            if(parentId==null){
                return;
            }
            this.setState({
                currentId: parentId,
                nameList: null,
            })
            this.closeCall(parentId);
            this.getFileList(parentId);
        });
    }

    // 搜索点击事件
    handleSearch = (value) => {
        console.log(this.state.currentId);
        var param = {};
      if(this.props.tabIndex == "1"){
            param.type = 'personal';
      }else  if(this.props.tabIndex == "2"){
            param.type = 'team';
      }
      param.nickname = value;
      param.parent = this.state.currentId;
      if(value == ""){
            this.getFileList(this.state.currentId);
      }else{
        this.getSearchFile(param);
      }
    }
  
    getSearchFile = async (param) => {
          const response = await API.getFile({ nickname: param.nickname, type: param.type,parent:param.parent});
          const { code, data } = response;
          console.log(data);
          if (code === 1) {
            const folders = this.orderFiles(this.seperateFiles(data, 'folder'), 'desc');
            const files = this.orderFiles(this.seperateFiles(data, 'pdf'), 'desc');
            const dataSource = [...folders, ...files];
            this.setState({
                dataSource,
                dirCount: folders.length,
                fileCount: files.length,
            });
          }
      }
  

    render () {
        var screenHeight = document.body.clientHeight;
        var screenWidth = window.screen.availWidth;
         // const imagelist =['http://ww3.sinaimg.cn/mw690/62aad664jw1f2nxvya0u2j20u01hc16p.jpg','http://ww1.sinaimg.cn/mw690/62aad664jw1f2nxvyo52qj20u01hcqeq.jpg'];
        // const onRow = record => ({
        //     onClick: () => {
        //         const { id, format } = record;
        //         if (format === 'folder') {
        //             this.getFileList(id);
        //             this.setState({
        //                 currentId: id,
        //             })
        //             this.closeCall(id);
        //         } else {
        //             this.props.changeMenu('fileDetail');
        //             this.props.changeCurrentID(id);
        //         }
        //     }
        // });
        const uploadedFilesColumns = [{
            title: '文件名称',
            dataIndex: 'nickname',
            key: 'nickname',
            render: (text, record) => this.renderColumns(text, record, 'nickname'),
        }, {
            title: '传输进度',
            dataIndex: 'percent',
            key: 'percent',
            render: (text, record) => (<Progress percent={record.percent} />),
        }, {
            title: '操作',
            dataIndex: 'operation',
            render: (text, record, index) => {
                const { editable } = record;
                return (
                    <div className="editable-row-operations">
                        {
                            editable ?
                                <a onClick={() => this.save(record.uid)}>保存</a>
                                : (
                                    <span>
                    <a onClick={() => this.edit(record.uid)}>编辑</a>
                    <Divider type="vertical" />
                    <a onClick={() => this.remove(index)}>删除</a>
                  </span>
                                )
                        }
                    </div>
                );
            },
        }];
        return (
            <div className="file-list-wrapper" style={{padding:20}}>
                <Modal
                    title="新建文件夹"
                    visible={this.state.visibleOfDir}
                    okText="确认"
                    cancelText="取消"
                    onOk={this.handleAddDir}
                    onCancel={() => this.handleHideModal('visibleOfDir')}
                >
                    <Row type="flex" align="middle">
                        <Col span={6} style={{ textAlign: 'right', paddingRight: 10 }}>
                            文件夹名称
                        </Col>
                        <Col span={18}>
                            <Input addonAfter="设置权限" onChange={(e) => { this.setState({ dirName: e.target.value }); }} />
                        </Col>
                    </Row>
                </Modal>
                <Modal
                    width={800}
                    title="上传文件"
                    visible={this.state.visibleOfFile}
                    okText="确认"
                    cancelText="取消"
                    onOk={this.handleUploadFile}
                    onCancel={() => this.handleHideModal('visibleOfFile')}
                >
                    <Row>
                        <Upload
                            accept=".pdf"
                            showUploadList={false}
                            customRequest={this.handleUpload}
                            onChange={this.finishUpload}>
                            <Button>本地上传</Button>
                        </Upload>
                        <Button style={{ marginLeft: 10 }}>云端上传</Button>
                    </Row>
                    <Divider />
                    <Table rowKey="uid" pagination={false} dataSource={this.state.uploadedFiles} columns={uploadedFilesColumns} />
                </Modal>
                <div className="operate-wrapper">
                {
                    this.props.tabIndex == "1" ?
                <Button style={{position:'absolute',top:'2%',right:'3%'}} icon="rollback"  id="backUp" type="primary" onClick={() => this.closeBack()}>返回</Button>
                :
                <Button style={{position:'absolute',top:'3%',right:'3%'}} icon="rollback"  id="backUp" type="primary" onClick={() => this.closeBack()}>返回</Button>
                }
                </div>
                {
                    this.props.tabIndex == "1" ?
                    [<div className="operate-wrapper">
                    <Button icon="folder" onClick={() => this.setState({ visibleOfDir: true })}>
                        新建文件夹
                    </Button> 
                    <Button icon="upload" type="primary" style={{ marginLeft: 20 }} onClick={() => this.setState({ visibleOfFile: true,uploadedFiles:[]})}>上传文件</Button>
                    <Search placeholder="文件名/文件夹名/标签/客户名称" enterButton="查询" size="large" style={{float:'right',width:400}}  onSearch={this.handleSearch}/>
                </div>]:
                [<div className="operate-wrapper">
                 <Search placeholder="文件名/文件夹名/标签/客户名称" enterButton="查询" size="large" style={{float:'right',width:400,marginBottom:12}}  onSearch={this.handleSearch} />
            </div>]
                }
                       
                <TMTable scroll={{y:screenHeight-385}} columns={this.state.columns} dataSource={this.state.dataSource} />
                <div style={{ fontSize: '14px', color: '#b0b0b0', marginTop: 20 }}>{this.state.dirCount}个文件夹，{this.state.fileCount}个文件</div>
            </div>
        );
    }
}

FileList.propTypes = {
    tabIndex: PropTypes.number.isRequired,
    changeMenu: PropTypes.func.isRequired,
    changeCurrentID: PropTypes.func.isRequired,
    returnName: PropTypes.func.isRequired,
};

const mapDispatchToProps = dispatch => ({
    changeMenu: selectedMenu => dispatch(changeMenu(selectedMenu)),
    changeCurrentID: selectedFileID => dispatch(FileAction.changeCurrentID(selectedFileID)),
});

export default connect(state => state, mapDispatchToProps)(FileList);
// export default  FileList;